<template>
  <div class="add-guide">
    <el-tabs v-model="guideActive" type="card" >
      <el-tab-pane label="普通网址" name="first">
        <el-form>
          <el-form-item label="单条或多条网址URL: (一行一个, http:// 或 https:// 开头)">
            <el-input type="textarea" :rows="10" v-model="normalUrl"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="批量网址" name="second">
        <el-form label-width="80px">
          <el-form-item label="地址格式">
            <div class="domain-scheme">
              <input type="text" class="domain-input" v-model="batch.url"/>
              <el-button type="text" @click="insertContent(`[地址参数]`)">[地址参数]</el-button>
            </div>
            <small-tip v-slot:content>[地址参数]表示地址中具有一定规律性的区域, 可用下列四种方式进行定义, 可设置多个.</small-tip>
          </el-form-item>
          <el-form-item label="[地址参数]" v-if="!batch.multi">
            <el-row>
              <el-col :span="4"><el-radio v-model="batch.type" :label="0">数字变化</el-radio></el-col>
              <el-col :span="20">
                <div>
                  从<el-input-number size="mini" :controls="false" v-model="batch.numChange.start" :disabled="batch.type !== 0" type="number" class="number-input" />开始, 每次递增
                  <el-input-number size="mini" :controls="false" v-model="batch.numChange.add" :disabled="batch.type !== 0" type="number" class="number-input" />, 共
                  <el-input-number size="mini" :controls="false" v-model="batch.numChange.total" :disabled="batch.type !== 0" type="number" class="number-input" />项
                  <span class="checkbox-group">
                    <el-checkbox v-model="batch.numChange.reverse" :disabled="batch.type !== 0">倒序</el-checkbox>
                    <el-checkbox v-model="batch.numChange.zero" :disabled="batch.type !== 0">补零</el-checkbox>
                  </span>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="4"><el-radio v-model="batch.type" :label="1">字母变化</el-radio></el-col>
              <el-col :span="20">
                <div>
                  从<el-input v-model="batch.letterChange.start" :disabled="batch.type !== 1" type="text" size="mini" class="number-input" />到
                  <el-input v-model="batch.letterChange.end" :disabled="batch.type !== 1" type="text" size="mini" class="number-input" />(区分大小写)
                  <span class="checkbox-group">
                    <el-checkbox v-model="batch.letterChange.reverse" :disabled="batch.type !== 1">倒序</el-checkbox>
                  </span>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="4"><el-radio v-model="batch.type" :label="2">时间变化</el-radio></el-col>
              <el-col :span="12">
                <div>
                  时间样式:
                  <input class="time-style-input" v-model="batch.timeChange.style" ref="timeStyle" :disabled="batch.type !== 2"/>
                  <el-dropdown trigger="click" @command="timeStyle">
                    <el-button circle icon="el-icon-edit" size="mini" :disabled="batch.type !== 2"></el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="YYYY">[年-YYYY]</el-dropdown-item>
                      <el-dropdown-item command="MM">[月-MM]</el-dropdown-item>
                      <el-dropdown-item command="DD">[日-DD]</el-dropdown-item>
                      <el-dropdown-item command="HH">[时-HH]</el-dropdown-item>
                      <el-dropdown-item command="mm">[分-mm]</el-dropdown-item>
                      <el-dropdown-item command="ss">[秒-ss]</el-dropdown-item>
                      <el-dropdown-item command="timestamp">时间戳</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </el-col>
              <el-col :span="8">
                <div>起始日期: 今天+ <el-input-number v-model="batch.timeChange.start" :disabled="batch.type !== 2" class="number-input" size="mini" :controls="false"/></div>
                <div>结束日期: 今天+ <el-input-number v-model="batch.timeChange.end" :disabled="batch.type !== 2" class="number-input" size="mini" :controls="false"/></div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="4"><el-radio v-model="batch.type" :label="3">自定义列表</el-radio></el-col>
              <el-col :span="15">
                <el-input v-model="batch.customList.content" :disabled="batch.type !== 3" type="textarea" :rows="3" resize="none"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-table :data="batch.multiParams" v-else>
            <el-table-column label="参数名" prop="name"></el-table-column>
            <el-table-column label="参数格式">
              <template slot-scope="scope">
                {{scope.row.type | paramFormat}}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80px">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="editSite(scope)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <el-dialog
          title="编辑: [地址参数]"
          :visible.sync="editDialog"
          :append-to-body="true">
          <el-form label-width="40px">
            <el-form-item>
              <el-row>
                <el-col :span="4"><el-radio v-model="edit.type" :label="0">数字变化</el-radio></el-col>
                <el-col :span="20">
                  <div>
                    从<input v-model="edit.numChange.start" :disabled="edit.type !== 0" type="number" class="number-input">开始, 每次递增
                    <input v-model="edit.numChange.add" :disabled="edit.type !== 0" type="number" class="number-input">, 共
                    <input v-model="edit.numChange.total" :disabled="edit.type !== 0" type="number" class="number-input">项
                    <span class="checkbox-group">
                      <el-checkbox v-model="edit.numChange.reverse" :disabled="edit.type !== 0">倒序</el-checkbox>
                      <el-checkbox v-model="edit.numChange.zero" :disabled="edit.type !== 0">补零</el-checkbox>
                    </span>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="4"><el-radio v-model="edit.type" :label="1">字母变化</el-radio></el-col>
                <el-col :span="20">
                  <div>
                    从<input v-model="edit.letterChange.start" :disabled="edit.type !== 1" type="text" class="number-input">到
                    <input v-model="edit.letterChange.end" :disabled="edit.type !== 1" type="text" class="number-input">(区分大小写)
                    <span class="checkbox-group">
                      <el-checkbox v-model="edit.letterChange.reverse" :disabled="edit.type !== 1">倒序</el-checkbox>
                    </span>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="4"><el-radio v-model="edit.type" :label="2">时间变化</el-radio></el-col>
                <el-col :span="12">
                  <div>
                    时间样式:
                    <input class="time-style-input" v-model="edit.timeChange.style" ref="timeStyle" :disabled="edit.type !== 2"/>
                    <el-dropdown trigger="click" @command="timeStyle">
                      <el-button circle icon="el-icon-edit" size="mini" :disabled="edit.type !== 2"></el-button>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="yyyy">[年-yyyy]</el-dropdown-item>
                        <el-dropdown-item command="MM">[月-MM]</el-dropdown-item>
                        <el-dropdown-item command="dd">[日-dd]</el-dropdown-item>
                        <el-dropdown-item command="HH">[时-HH]</el-dropdown-item>
                        <el-dropdown-item command="mm">[分-mm]</el-dropdown-item>
                        <el-dropdown-item command="ss">[秒-ss]</el-dropdown-item>
                        <el-dropdown-item command="timestamp">时间戳</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div>起始日期: 今天+ <input v-model="edit.timeChange.start" :disabled="edit.type !== 2" type="text" class="number-input"></div>
                  <div>结束日期: 今天+ <input v-model="edit.timeChange.end" :disabled="edit.type !== 2" type="text" class="number-input"></div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="4"><el-radio v-model="edit.type" :label="3">自定义列表</el-radio></el-col>
                <el-col :span="15">
                  <el-input :disabled="edit.type !== 3" type="textarea" :rows="3" resize="none"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="editDialog = false">确 定</el-button>
          </span>
        </el-dialog>
        <div>
          <el-input v-model="reviewList" type="textarea" :rows="5" resize="none" :disabled="true"></el-input>
        </div>
      </el-tab-pane>
      <el-tab-pane label="文本导入" name="third">
        <el-form label-width="80px">
          <el-form-item label="文本位置">
            <div class="file-import-block">
              <el-input size="mini" v-model="fileName" placeholder="该文本内容, 每行将作为一个起始网址"></el-input>
              <label for="file-import" class="import-btn">
                ...
              </label>
            </div>
            <input style="display: none;" id="file-import" type="file" @change="fileChange" accept=".txt">
          </el-form-item>
          <el-input type="textarea" v-model="importContent" :autosize="{ minRows: 10, maxRows: 10 }" disabled resize="none">
          </el-input>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="数据库导入" name="forth">
        <el-form label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="数据库类型">
                <el-select v-model="dataBase.type" size="mini">
                  <el-option label="MySql" :value="0"></el-option>
                  <el-option label="SqlServer" :value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="数据库地址">
                <el-input v-model="dataBase.host" size="mini"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据库端口">
                <el-input v-model="dataBase.port" size="mini"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="数据库用户">
                <el-input v-model="dataBase.user" size="mini"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据库密码">
                <el-input v-model="dataBase.password" type="password" size="mini"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="数据库库名">
                <el-input v-model="dataBase.dbname" size="mini"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据库编码">
                <el-select v-model="dataBase.encoding" size="mini">
                  <el-option label="utf8" value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="数据库表名">
                <el-input v-model="dataBase.table" size="mini"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据所在列">
                <el-input v-model="dataBase.column" size="mini"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <div class="btn-group">
      <el-button size="small" @click="cancel">取 消</el-button>
      <el-button type="primary" size="small" @click="submit">确 定</el-button>
    </div>
  </div>
</template>
<script>
import insertText from '@/utils/insertText'
import SmallTip from '@/components/SmallTip'
import dayjs from 'dayjs'
export default {
  name: 'AddGuide',
  components: {
    SmallTip
  },
  data () {
    return {
      guideActive: 'first',
      normalUrl: 'http://',
      editDialog: false,
      edit: {
        type: 0,
        numChange: {
          start: 1,
          add: 1,
          total: 5,
          reverse: false,
          zero: false
        },
        letterChange: {
          start: 'a',
          end: 'z',
          reverse: false
        },
        timeChange: {
          style: 'yyyyMMdd',
          start: null,
          end: null
        },
        customList: {
          content: ''
        }
      },
      batch: {
        url: 'http://',
        multi: false,
        multiParams: [],
        type: 0,
        numChange: {
          start: 1,
          add: 1,
          total: 5,
          reverse: false,
          zero: false
        },
        letterChange: {
          start: 'a',
          end: 'z',
          reverse: false
        },
        timeChange: {
          style: 'YYYYMMDD',
          start: 0,
          end: 0
        },
        customList: {
          content: ''
        }
      },
      reviewList: '',
      importContent: '',
      fileName: '',
      dataBase: {
        type: null,
        host: '',
        port: null,
        user: '',
        password: '',
        dbname: '',
        encoding: null,
        table: '',
        column: null
      }
    }
  },
  filters: {
    paramFormat: function (p) {
      const obj = {
        0: '数字变化',
        1: '字母变化',
        2: '时间变化',
        3: '自定义列表'
      }
      return obj[p]
    }
  },
  methods: {
    /**
     * 向指针处插入
     */
    insertContent (content) {
      if (!content) { // 如果插入的内容为空则返回
        return
      }
      const dom = document.querySelector('.domain-input')
      insertText(dom, content)
      this.batch.url = dom.value
    },
    timeStyle (v) {
      const dom = document.querySelector('.time-style-input')
      insertText(dom, v)
      this.batch.timeChange.style = dom.value
    },
    fileChange (e) {
      const file = e.target.files[0]
      console.log(file)
      this.fileName = file.name
      const reader = new FileReader()
      reader.onload = (evt) => {
        this.importContent = evt.target.result
      }
      reader.readAsText(file)
    },
    submit () {
      let obj = {}
      if (this.guideActive === 'first') {
        if (this.normalUrl === '' || this.normalUrl === 'http://' || this.normalUrl === 'https://') return
        let arr = this.normalUrl.trim().split('\n')
        obj.type = 'first'
        obj.urlArr = arr
      } else if (this.guideActive === 'second') {
        if (!this.batch.multi) {
          if (this.batch.url === 'http://' || this.batch.url === 'https://') {
            return
          } else {
            obj.type = 'first'
            obj.urlArr = [this.batch.url]
          }
        } else {
          obj.type = 'second'
        }
      } else if (this.guideActive === 'third') {
        obj.type = 'third'
      } else if (this.guideActive === 'forth') {
        obj.type = 'forth'
      }
      this.$emit('submit', obj)
    },
    cancel () {
      this.$emit('cancel')
    },
    editSite (scope) {
      this.editDialog = true
    },
    /**
     * 时间格式化
     * @param {String} style 格式
     * @param {Number} day 天数
     * @param {String} url 需要替换的url
     */
    timeFormat (style, day, url) {
      let YYYY, MM, DD, HH, mm, ss, timestamp
      if (day === 0) {
        YYYY = dayjs().format('YYYY')
        MM = dayjs().format('MM')
        DD = dayjs().format('DD')
        HH = dayjs().format('HH')
        mm = dayjs().format('mm')
        ss = dayjs().format('ss')
        timestamp = dayjs().unix()
      } else if (day < 0) {
        let current = Math.abs(day)
        YYYY = dayjs().subtract(current, 'day').format('YYYY')
        MM = dayjs().subtract(current, 'day').format('MM')
        DD = dayjs().subtract(current, 'day').format('DD')
        HH = dayjs().subtract(current, 'day').format('HH')
        mm = dayjs().subtract(current, 'day').format('mm')
        ss = dayjs().subtract(current, 'day').format('ss')
        timestamp = dayjs().subtract(current, 'day').unix()
      } else if (day > 0) {
        YYYY = dayjs().add(day, 'day').format('YYYY')
        MM = dayjs().add(day, 'day').format('MM')
        DD = dayjs().add(day, 'day').format('DD')
        HH = dayjs().add(day, 'day').format('HH')
        mm = dayjs().add(day, 'day').format('mm')
        ss = dayjs().add(day, 'day').format('ss')
        timestamp = dayjs().add(day, 'day').unix()
      }
      let time = style.replace(/YYYY/g, YYYY).replace(/MM/g, MM).replace(/DD/g, DD).replace(/HH/g, HH).replace(/mm/g, mm).replace(/ss/g, ss).replace(/timestamp/g, timestamp)
      return url.replace(/\[地址参数\]/g, time)
    }
  },
  watch: {
    'batch.url': function () {
      let arr = this.batch.url.match(/\[地址参数\]/g)
      if (arr && arr.length > 1) {
        this.batch.multi = true
        this.batch.multiParams = []
        arr.forEach(v => {
          this.batch.multiParams.push({
            name: v,
            type: 0,
            numChange: {
              start: 1,
              add: 1,
              total: 5,
              reverse: false,
              zero: false
            },
            letterChange: {
              start: 'a',
              end: 'z',
              reverse: false
            },
            timeChange: {
              style: 'yyyyMMdd',
              start: null,
              end: null
            },
            customList: {
              content: ''
            }
          })
        })
      } else {
        this.batch.multi = false
        this.batch.multiParams = []
      }
    },
    // 更具数据变化修改预览显示
    batch: {
      handler: function () {
        if (this.batch.url.indexOf('[地址参数]') === -1) return
        if (this.batch.type === 0) { // 数字变化预览
          const num = this.batch.numChange
          let result = []
          let i = num.start
          let j = 0
          while (j < num.total) {
            result.push(this.batch.url.replace(/\[地址参数\]/g, i))
            i += num.add
            j++
          }
          if (num.total > 6) {
            if (num.reverse) {
              result = result.reverse()
            }
            result = [...result.slice(0, 3), '...', result[result.length - 1]]
          }
          this.reviewList = result.join('\n')
        } else if (this.batch.type === 1) { // 字母变化预览
          let { start, end, reverse } = this.batch.letterChange
          let result = []
          if (start === end) {
            if (start === '') {
              if (reverse) {
                ['z', 'y', 'x', '...', 'a'].forEach(v => {
                  result.push(this.batch.url.replace(/\[地址参数\]/g, v))
                })
              } else {
                ['a', 'b', 'c', '...', 'z'].forEach(v => {
                  result.push(this.batch.url.replace(/\[地址参数\]/g, v))
                })
              }
            } else {
              result.push(this.batch.url.replace(/\[地址参数\]/g, start))
            }
          } else {
            if (reverse) {
              [start, '...', end].forEach(v => {
                result.push(this.batch.url.replace(/\[地址参数\]/g, v))
              })
            } else {
              [end, '...', start].forEach(v => {
                result.push(this.batch.url.replace(/\[地址参数\]/g, v))
              })
            }
          }
          this.reviewList = result.join('\n')
        } else if (this.batch.type === 2) { // 时间变化预览
          let { start, end, style: timeStyle } = this.batch.timeChange
          let result = []
          if (start > end) return
          if (timeStyle === '') {
            let style = 'MM/DD/YYYY HH:mm:ss'
            if (start === end) {
              result = [this.timeFormat(style, start, this.batch.url)]
            } else {
              let endTime = this.timeFormat(style, end, this.batch.url)
              let startTime = this.timeFormat(style, start, this.batch.url)
              if (end - start >= 6) {
                result = [startTime, this.timeFormat(style, start + 1, this.batch.url), this.timeFormat(style, start + 2, this.batch.url), '...', endTime]
              } else {
                for (let i = 0; i < end - start; i++) {
                  result.push(this.timeFormat(style, start + i, this.batch.url))
                }
              }
            }
          } else {
            if (start === end) {
              result = [this.timeFormat(timeStyle, start, this.batch.url)]
            } else {
              let endTime = this.timeFormat(timeStyle, end, this.batch.url)
              let startTime = this.timeFormat(timeStyle, start, this.batch.url)
              if (end - start >= 6) {
                result = [startTime, this.timeFormat(timeStyle, start + 1, this.batch.url), this.timeFormat(timeStyle, start + 2, this.batch.url), '...', endTime]
              } else {
                for (let i = 0; i < end - start; i++) {
                  result.push(this.timeFormat(timeStyle, start + i, this.batch.url))
                }
              }
            }
          }
          this.reviewList = result.join('\n')
        } else if (this.batch.type === 3) { // 自定义列表
          let content = this.batch.customList.content
          if (content !== '') {
            let list = content.trim().split('\n')
            let result = []
            list.forEach(v => {
              result.push(this.batch.url.replace(/\[地址参数\]/g, v))
            })
            this.reviewList = result.join('\n')
          } else {
            this.reviewList = ''
          }
        }
      },
      deep: true
    }
  }
}
</script>
<style lang="scss">
.add-guide {
  min-height: 415px;
  input:disabled {
    background-color: #f5f7fa;
    border: 1px solid #E4E7ED;
    color: #C0C4CC;
    cursor: not-allowed;
  }
  .domain-scheme {
    display: flex;
    align-items: center;
  }
  .domain-input {
    flex: 1;
  }
  .param-item {
    display: block;
  }
  .number-input {
    width: 47px;
    margin: 0 5px;
  }
  .checkbox-group {
    display: inline;
    padding-left: 20px;
  }
  .file-import-block {
    display: flex;
    align-items: center;
  }
  .import-btn {
    display: inline-block;
    height: 28px;
    width: 48px;
    line-height: 22px;
    text-align: center;
    color: #fff;
    background-color: #909399;
    border-color: #909399;
    &:hover {
      background: #a6a9ad;
      border-color: #a6a9ad;
      color: #fff;
    }
  }
  .btn-group {
    padding-top: 20px;
    text-align: right;
  }
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type="number"]{
    -moz-appearance: textfield;
  }
}
</style>
